package get

import (
	"database/sql"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Gettestuser(r *gin.Engine) {
	var db *sql.DB
	var err error
	var sid, mal, date string = "0", "0", "0"

	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)
	db, err = sql.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}

	// 获取搜索
	r.GET("/gettestlog", func(c *gin.Context) {
		xx := c.Query("xx")
			str := ""
			if len(xx)==0 {
				str = "SELECT * FROM public.testlog"
			} else {
				
				str = "SELECT * FROM public.testlog where sid='" + xx + "'"
			}

			// str := "SELECT * FROM public.testlog where sid='" + xx + "'"
			rows, err := db.Query(str)
			if err != nil {
				panic(err)
			}

			for rows.Next() {

				err = rows.Scan(&sid, &mal, &date)
				if err != nil {
					panic(err)
				}

				c.JSON(200, gin.H{
					"sid":  sid,
					"mal":  mal,
					"date": date,
				})
			}

	})

	// 添加用户
	r.GET("/inserttestlog", func(c *gin.Context) {
		sid = c.Query("sid")
		mal = c.Query("mal")
		date = c.Query("date")

		if err != nil {
			panic(err)
		}
		str := "INSERT INTO public.testlog(sid,mal,date) VALUES($1,$2,$3)"
		stmt, err := db.Prepare(str)
		if err != nil {
			panic(err)
		}

		res, err := stmt.Exec(sid, mal, date)
		if err != nil {
			panic(err)
		}

		affect, err := res.RowsAffected()
		if err != nil {
			panic(err)
		}

		fmt.Println("rows affect:", affect)
	})

}
